<?php
function RenderTemplate($template,$values=array(),$prepend='')
{
	$tite_prepend = '<!--@';
	$tite_postpend = '-->';

	// Escape regular expression keywords
	$regexp_keys = array('[',']','+','?','*');
	$regexp_replace = array('\[','\]','\+','\?','\*');
	$tite_prepend_es = str_replace($regexp_keys,$regexp_replace,$tite_prepend);
	$tite_postpend_es = str_replace($regexp_keys,$regexp_replace,$tite_postpend);

	// Remove all template-specific characters from found keys
	$replacements = array('+','-','>');
	$str = $tite_prepend.$tite_postpend;
	for($i=0;$i<strlen($str);$i++)
	{
		$replacements[] = $str[$i];
	}
	$replacements = array_unique($replacements);

	// Find all + and - logic blocks and remove the sections if appropriate
	preg_match_all('/'.$tite_prepend_es.'[\+-][^\]]*?'.$tite_postpend_es.'/',$template,$matches);
	if(count($matches) && count($matches[0]))
	{
		$matches[0] = array_unique($matches[0]);
		foreach($matches[0] as $key)
		{
			$key = $prepend.$key;;
			$empty = empty($values[str_replace($replacements,'',$key)]);
			$index = strlen($tite_prepend);
			if(($key[$index] == '+' && $empty) || ($key[$index] == '-' && !$empty))
			{
				$startIndex = $endIndex = 0;
				while($startIndex !== false && $endIndex < strlen($template))
				{
					$startIndex = strpos($template,$key,$endIndex);
					$endIndex = strpos($template,$key,$startIndex+1);
					if($endIndex !== false)
					{
						$endIndex += strlen($key);

						$template = substr($template,0,$startIndex).substr($template,$endIndex);
					}
					else break;
				}
			}
		}
	}

	// Loop through the arrays passed in and replace values in template
	foreach($values as $key=>$value)
	{
		$key = $prepend.$key;
		if(is_array($value))
		{
			$formattedKey = $tite_prepend.'>'.$key.$tite_postpend;
			$startIndex = $endIndex = 0;
			while($startIndex !== false && $endIndex < strlen($template))
			{
				$startIndex = strpos($template,$formattedKey,$startIndex);
				if($startIndex !== false)
				{
					$startIndex += strlen($formattedKey);
					$endIndex = strpos($template,$formattedKey,$startIndex);
					if($endIndex !== false)
					{
						$a = substr($template,$startIndex,$endIndex-$startIndex);
						$html = '';
						foreach($value as $arr)
						{
							$html .= RenderTemplate($a,$arr,$key.'.');
						}
						$template = substr($template,0,$startIndex).$html.substr($template,$endIndex);
					}
					else $endIndex = $startIndex+1;
				}
			}
		}
		else
		{
			$formattedKey = $tite_prepend.$key.$tite_postpend;
			$template = str_replace($formattedKey,$value,$template);
		}
	}

	// Remove any lingering template items
	$template = preg_replace('/'.$tite_prepend_es.'[^\]]*?'.$tite_postpend_es.'/','',$template);
	return $template;
}
?>
